from django.db.models import Q
from rest_framework.views import APIView
from app01.models import IDCDevice, Client, Cabinet, MachineRoom
from django.http import JsonResponse, HttpResponse
from app01.Baseview import BasedAPIView


class MachRoomView(BasedAPIView):
    def get(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'get_room_all':
            return self.get_room_all(request)

    def post(self, request, *args, **kwargs):
        module = kwargs.get('module')
        if module == 'add':
            return self.add(request)
        if module == 'edit':
            return self.edit(request)
        if module == 'dele':
            return self.dele(request)

    def get_room_all(self, request):
        uid = request.GET.get('id', None)
        room_name = request.GET.get('room_name', None)
        query = Q()
        if uid is not None:
            query &= Q(id=uid)
        if room_name is not None:
            query &= Q(room_name__icontains=room_name)

        rooms = MachineRoom.objects.filter(query).order_by('-id')
        total = rooms.count()
        room_dic = []
        for item in rooms:
            data = {
                'id': item.id,
                'name': item.room_name,
            }
            room_dic.append(data)
        res_data = {
            'total': total,
            'data': room_dic
        }
        return super().success(data=res_data)

    def add(self, request):
        room_name = request.data.get('name')
        if not room_name:
            return super().error(msg="机房名称不能为空")
        try:
            room = MachineRoom(room_name=room_name)
            room.save()
            data = {
                'id': room.id,
                'name': room.room_name,
            }
            return super().success(msg="新增成功", data=data)
        except Exception as e:
            return super().error(msg=str(e))

    def edit(self, request):
        uid = request.data.get('id')
        name = request.data.get('name')
        try:
            room = MachineRoom.objects.get(id=uid)
            room.room_name = name
            room.save()
            data = {
                'id': room.id,
                'name': room.room_name,
            }
            return super().success(msg="修改成功", data=data)
        except Exception as e:
            return super().error(msg=str(e))

    def dele(self, request):
        '''删除数据'''
        ids = request.GET.get("id", "")
        if ids == "":
            return super().error(msg="ID不能为空")
        ids = ids.split(",")  # 将字符串切割为列表
        ids_int = []
        for i in ids:
            if i == "":
                continue
            ids_int.append(int(i))  # 将id转换为数字类型 然后添加到新的列表中
        Obj = MachineRoom.objects.filter(id__in=ids_int)  # id__in为 根据id字段 传入一个列表 批量查询需要删除的数据
        if not Obj.exists():  # 检测数据是否存在
            return super().error(msg="数据不存在")
        if Obj.filter(cabinets__isnull=False).exists():
            return super().error(msg="该机房下有机柜，先删除机柜在删除机房")
        Obj.delete()  # 删除查询到的数据
        return super().success(msg="删除成功")
